import React, { Component } from 'react'
import SearchHeader from '../../components/SearchHeader'
import { Flex, Toast } from 'antd-mobile'
import Filter from './components/Filter'
import styles from './index.module.scss'
import { API } from '../../utils/axios'
import HouseItem from '../../components/HouseItem'
import Sticky from '../../components/Sticky'

export default class HouseList extends Component {

  state = {
    list: [], // 列表数据
    count: 0,
    start: 1,
    end: 20
  };
  cityName = '';
  cityId = '';

  filters = {};
  allHeight = 0; // 屏幕实际dom元素高度

  async componentDidMount() {
    // 获取城市名
    const { label, value } = JSON.parse(localStorage.getItem('hkzf_city'))
    this.cityName = label;
    this.cityId = value;
    await this.searchHouseList();
    // 数据加载完时再添加事件
    this.infinteLoader();
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.loadScroll);
  }

  render() {
    return (
      <div>
        <Flex id={styles.header}>
          <span className="iconfont icon-back" onClick={() => this.props.history.goBack()}></span>
          {/* 搜索框 */}
          <SearchHeader className={styles.searchHeader} cityName={this.cityName} />
        </Flex>
        {/* 条件筛选 */}
        <Sticky>
          <Filter onFilter={this.onFilter} />
        </Sticky>
        {/* 渲染房源列表 */}
        <HouseItem housesList={this.state.list} />
      </div>
    )
  }

  // 拿到筛选数据
  onFilter = (filters) => {
    this.filters = filters;
    this.searchHouseList();
  }

  // 搜索获取房屋列表 // 是否触底参数
  async searchHouseList(loader = false) {
    Toast.loading('加载中...');
    const { start, end } = this.state;
    const { data } = await API.get('/houses', {
      params: {
        cityId: this.cityId,
        ...this.filters,
        start,
        end
      }
    });
    Toast.hide();
    // console.log(data);

    const { list, count } = data.body;
    // console.log(this.state.list,'@@', list);
    // 如果是触底加上新的，如果不是重新获取新的
    this.setState({
      list: loader ? [...this.state.list, ...list] : list, 
      count
    });
    // 重新获取高度
    this.allHeight = document.body.scrollHeight;
  }

  /**
   * 无限加载列表
   * 1.添加滚动事件
   * 2.滚动触底
   *  => 公式: 屏幕总高度 - 被卷去的高度 === 屏幕可见高度
   * 3.更新数据
   *  1.开始页码等于结束页码 + 1
   *  2.结束页码 += 10
   *  3.发起请求
   */
  infinteLoader() {
    window.addEventListener('scroll', this.loadScroll());
  }
  // 事件逻辑，方便销毁
  loadScroll = () => {
    // 函数柯里化
    return async () => {
      // 屏幕总高度 - 被卷去的高度
      let remainingHeight = this.allHeight - document.documentElement.scrollTop;
      let clientHeight = document.body.offsetHeight;
      // console.log(remainingHeight);
      if (remainingHeight === clientHeight) {
        // 触底后
        const { end, count, start } = this.state;
        if (end >= count || start >= count) return alert('没有更多数据了！');
        const newStart = end + 1;
        const newEnd = newStart + 19;
        this.setState({
          start: newStart >= count ? count : newStart,
          end: newEnd >= count ? count : newEnd // 如果全部数据拿到
        });
        await this.searchHouseList(true);
      }
    }
  }
}
